//go:build windows

package filelib

import (
	"bufio"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/urfave/cli/v2"
	"io"
	"os"
)

var (
	BuildTime string
	Version   = "1.0.0"
)

func Do() {
	app := cli.NewApp()
	app.Name = "idp-file-cli"
	app.Version = fmt.Sprintf("%s build:%s", Version, BuildTime)
	app.Usage = "为 idp 提供文件操作"
	app.Description = "文件信息包括：获取文件信息，检查文件是否存在、获取文件md5、删除文件"
	app.Flags = []cli.Flag{
		&cli.StringFlag{
			Name:    "path",
			Aliases: []string{"p"},
			Usage:   "获取文件信息",
		},
		&cli.StringFlag{
			Name:    "md5",
			Aliases: []string{"m"},
			Usage:   "获取文件md5",
		},
		&cli.StringFlag{
			Name:    "delete",
			Aliases: []string{"d"},
			Usage:   "删除文件",
		},
		&cli.Int64Flag{
			Name:    "taskId",
			Aliases: []string{"id"},
			Usage:   "任务id",
		},
	}
	app.Action = func(ctx *cli.Context) error {
		var (
			path   string
			bs     []byte
			err    error
			taskId int64
		)
		if ctx.IsSet("taskId") {
			taskId = ctx.Int64("taskId")
		}
		path = ctx.Path("path")
		if path == "" {
			return errors.New("请输入文件路径")
		}
		if ctx.IsSet("delete") {
			err = os.RemoveAll(path)
			return err
		}
		r := fileInfo(path)
		if ctx.IsSet("md5") {
			bs = []byte(r.Md5)
		} else {
			r.TaskId = taskId
			if bs, err = json.Marshal(r); err != nil {
				return err
			}
		}
		w := bufio.NewWriter(os.Stdout)
		w.Write(bs)
		w.WriteString("\n")
		return w.Flush()
	}
	if err := app.Run(os.Args); err != nil {
		fmt.Printf("命令行调用错误：%s ，请查看帮助文档", err.Error())
	}
}

type RFile struct {
	TaskId   int64  `json:"taskId,string"`
	FileSize int64  `json:"fileSize,string"`
	Md5      string `json:"md5"`
	FilePath string `json:"filePath"`
	IsExist  bool   `json:"isExist"`
}

// fileInfo b-文件是否存在
func fileInfo(fp string) (info RFile) {
	f, err := os.Stat(fp)
	if err != nil {
		return
	}
	if f.IsDir() {
		return
	}
	str, err := fileMd5(fp)
	if err != nil {
		return
	}
	info = RFile{
		FileSize: f.Size(),
		Md5:      str,
		FilePath: fp,
		IsExist:  true,
	}
	return
}

func fileMd5(fp string) (str string, err error) {
	file, err := os.Open(fp)
	if err != nil {
		return "", err
	}
	defer file.Close()
	hash := md5.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	return hex.EncodeToString(hash.Sum(nil)), nil
}
